import * as THREE from 'three';
import { gsap } from 'gsap';
/**
* 创建包围盒平面组（包含6个平面和可选线框）
*/
export function createBoundingPlanes(bbox) {
    const group = new THREE.Group();
    const planeSize = {
        width: bbox.max.x - bbox.min.x,
        height: bbox.max.y - bbox.min.y,
        depth: bbox.max.z - bbox.min.z
    };

    const canvas = document.createElement('canvas');
    canvas.width = 256;
    canvas.height = 256;
    const context = canvas.getContext('2d');
    const gradient = context.createLinearGradient(0, 0, 0, canvas.height);
    gradient.addColorStop(0, 'rgba(255, 0, 0, 0)');  // 底部完全不透明红色
    gradient.addColorStop(1, 'rgba(255, 0, 0, 1)');  // 顶部完全透明

    context.fillStyle = gradient;
    context.fillRect(0, 0, canvas.width, canvas.height);

    // 3. 创建CanvasTexture
    const texture = new THREE.CanvasTexture(canvas);
    texture.wrapS = THREE.RepeatWrapping; // 关键：允许重复

    // 平面材质（半透明）
    const planeMaterial = new THREE.MeshBasicMaterial({
        side: THREE.DoubleSide,
        transparent: true,
        opacity: 0,
        map: texture
    });

    gsap.to(planeMaterial, {
        opacity: 1,  // 负值表示向上移动
        duration: 1,
        repeat: -1,
        yoyo: true,
        ease: "none",
        onUpdate: () => planeMaterial.needsUpdate = true
    });
    // 1. 前面 (Z = max.z)
    const frontPlane = new THREE.Mesh(
        new THREE.PlaneGeometry(planeSize.width, planeSize.height),
        planeMaterial
    );
    frontPlane.position.set(
        bbox.min.x + planeSize.width / 2,
        bbox.min.y + planeSize.height / 2,
        bbox.max.z
    );
    group.add(frontPlane);

    // 2. 后面 (Z = min.z)
    const backPlane = new THREE.Mesh(
        new THREE.PlaneGeometry(planeSize.width, planeSize.height),
        planeMaterial
    );
    backPlane.position.set(
        bbox.min.x + planeSize.width / 2,
        bbox.min.y + planeSize.height / 2,
        bbox.min.z
    );
    backPlane.rotation.y = Math.PI; // 旋转180度
    group.add(backPlane);

    // 3. 右面 (X = max.x)
    const rightPlane = new THREE.Mesh(
        new THREE.PlaneGeometry(planeSize.depth, planeSize.height),
        planeMaterial
    );
    rightPlane.position.set(
        bbox.max.x,
        bbox.min.y + planeSize.height / 2,
        bbox.min.z + planeSize.depth / 2
    );
    rightPlane.rotation.y = Math.PI / 2; // 旋转90度
    group.add(rightPlane);

    // 4. 左面 (X = min.x)
    const leftPlane = new THREE.Mesh(
        new THREE.PlaneGeometry(planeSize.depth, planeSize.height),
        planeMaterial
    );
    leftPlane.position.set(
        bbox.min.x,
        bbox.min.y + planeSize.height / 2,
        bbox.min.z + planeSize.depth / 2
    );
    leftPlane.rotation.y = -Math.PI / 2; // 旋转-90度
    group.add(leftPlane);

    return group;
}